import json
from gis.common import track_logging

from django.http import HttpResponse
from django.views.decorators.http import require_POST

from gis.common.django_ext.decorators import validate_parameters
from gis.common.exceptions import BizException
from itpay.core.recharge_order import order_service
from itpay.core.recharge_order import sms_recharge_service
from itpay.core.recharge_order.const import *
from itpay.core.recharge_order.errors import ERROR_IP_NOT_IN_WHITE_IPS
from itpay.utils.requests_utils import get_request_ip
from . import third_callback_form

_LOGGER = track_logging.getLogger(__name__)


@require_POST
@validate_parameters(third_callback_form.UploadSmsSchema)
def notify_sms(request, cleaned_data):
    ip = get_request_ip(request)
    if ip not in SMS_SERVICE_WHITE_IPS:
        raise BizException(ERROR_IP_NOT_IN_WHITE_IPS, ip)

    out_id = cleaned_data['id']
    phone = cleaned_data['phone']
    from_phone = cleaned_data['from_phone']
    content = cleaned_data['msg']
    sms_time = cleaned_data['created_at']
    if not sms_recharge_service.exists_sms(out_id):
        sms_recharge_service.save_sms(out_id, phone, from_phone, content, sms_time)
    return HttpResponse(json.dumps({'status': 'ok'}))


@require_POST
@validate_parameters(third_callback_form.TongLueCallBackSchema)
def tonglue_recharge_callback(request, cleaned_data):
    _LOGGER.info('tonglue recharge callback {}'.format(cleaned_data))
    ip = get_request_ip(request)
    if ip not in TONGLUE_CONF['white_ips']:
        raise BizException(ERROR_IP_NOT_IN_WHITE_IPS, ip)
    order = order_service.get_order(cleaned_data['order_id'])

    if OrderStatus(order['status']) == OrderStatus.CREATED:
        order_service.commit_order(cleaned_data['order_id'], remark='commit by tonglue callback')

    return HttpResponse(json.dumps({"success": 1}))



